package org.luckystrophe.snowtoms;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;
import org.luckystrophe.snowtoms.model.JsonRequest;
import org.luckystrophe.snowtoms.model.impl.LoginPost;
import org.luckystrophe.snowtoms.model.impl.MyProgressDialog;
import org.luckystrophe.snowtoms.model.impl.RequestInitializeClient;
import org.luckystrophe.snowtoms.pref.UserPreference_;

import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.widget.ImageView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;
import com.googlecode.androidannotations.annotations.AfterInject;
import com.googlecode.androidannotations.annotations.AfterViews;
import com.googlecode.androidannotations.annotations.Background;
import com.googlecode.androidannotations.annotations.Bean;
import com.googlecode.androidannotations.annotations.Click;
import com.googlecode.androidannotations.annotations.EActivity;
import com.googlecode.androidannotations.annotations.NoTitle;
import com.googlecode.androidannotations.annotations.UiThread;
import com.googlecode.androidannotations.annotations.ViewById;
import com.googlecode.androidannotations.annotations.sharedpreferences.Pref;

@EActivity(R.layout.activity_splash)
@NoTitle
public class SplashActivity extends SherlockActivity {

	@ViewById(R.id.iv_myIv)
	ImageView miv;

	// @ViewById(R.id.iv_myIv)
	// MovingImageView miv;

	@ViewById(R.id.iv_mainlogo)
	ImageView iv_mainlogoCanvas;

	@Bean(LoginPost.class)
	JsonRequest loginPost;

	@Bean(RequestInitializeClient.class)
	JsonRequest initClient;

	@Bean
	MyProgressDialog pDialog;

	@Pref
	UserPreference_ pref;

	AnimationDrawable logoAnimation;

	private boolean isCancelDialog = false;

	@AfterInject
	public void afterInject() {
		initializeClient();
	}

	@AfterViews
	public void afterViews() {
		startLogoAnimation();
	}

	public void goNextActivity() {
		if (isCancelDialog) {
			isCancelDialog = false;
			return;
		} else {
			Intent intent = new Intent(this, MainActivity_.class);
			startActivity(intent);
			overridePendingTransition(R.anim.fadein, R.anim.deltazero);
			logoAnimation.stop();
			finish();
		}

	}

	@Click(R.id.iv_myIv)
	public void clickBackground() {
		pDialog.showProgressDialog(this, new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				isCancelDialog = true;
				miv.setClickable(true);
			}
		}, new OnDismissListener() {
			@Override
			public void onDismiss(DialogInterface dialog) {
				goNextActivity();
			}
		});
		miv.setClickable(false);
		afterTouchScreen();
	}

	@Background
	public void afterTouchScreen() {
		final Timer mTimer = new Timer();
		TimerTask mTask = new TimerTask() {
			@Override
			public void run() {
				openFacebookSession();
				mTimer.cancel();
			}
		};
		mTimer.schedule(mTask, 1000);
	}

	@Background
	public void getConnection() {
		try {
			afterGetConnection(loginPost.sendJsonRequest());
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@UiThread
	public void afterGetConnection(JSONObject jo) {
		((LoginPost) loginPost).getAuthcode(jo);
		pDialog.cancelProgressDialog();
	}

	@Background
	public void initializeClient() {
		JSONObject resultJo = new JSONObject();
		try {
			resultJo = initClient.sendJsonRequest();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		afterInitialize(resultJo);
	}

	@UiThread
	public void afterInitialize(JSONObject resultJo) {
		try {
			((RequestInitializeClient) initClient).parseResultJson(resultJo);
		} catch (JSONException je) {
			je.printStackTrace();
			Toast.makeText(this, "에러 발생 ! ", Toast.LENGTH_SHORT).show();
		}
	}

	public void openFacebookSession() {
		Session.openActiveSession(this, false, new StatusCallback() {
			@Override
			public void call(final Session session, SessionState state, Exception exception) {
				Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
					@Override
					public void onCompleted(GraphUser user, Response response) {
						if (user != null) {
							pref.fbAuthCode().put(session.getAccessToken());
							pref.collaboId().put(user.getId());
							pref.name().put(user.getName());
						}
					}
				});
				Request.executeBatchAsync(request);
			}
		});
		getConnection();
	}

	public class AnimationStater implements Runnable {
		@Override
		public void run() {
			logoAnimation.start();
		}

	}

	@SuppressWarnings("deprecation")
	@UiThread
	public void startLogoAnimation() {
		logoAnimation = new AnimationDrawable();

		logoAnimation.addFrame(getResources().getDrawable(R.drawable.intro_logo01), 400);
		logoAnimation.addFrame(getResources().getDrawable(R.drawable.intro_logo02), 400);

		logoAnimation.setOneShot(false);
		iv_mainlogoCanvas.setBackgroundDrawable(logoAnimation);
		iv_mainlogoCanvas.post(new AnimationStater());
	}

	@Override
	public void onPause() {
		super.onPause();
		logoAnimation.stop();
	}

}
